package com.yserp.project.erp.order.deliveryorder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yserp.common.exception.BusinessException;
import com.yserp.common.utils.StringUtils;
import com.yserp.common.utils.bean.BeanUtils;
import com.yserp.common.utils.mybatis.MybatisPlusUtil;
import com.yserp.common.utils.text.Convert;
import com.yserp.project.erp.common.enums.CheckStatusEnums;
import com.yserp.project.erp.common.enums.OrderEnums;
import com.yserp.project.erp.order.deliveryorder.domain.DeliveryOrder;
import com.yserp.project.erp.order.deliveryorder.domain.DeliveryOrderDto;
import com.yserp.project.erp.order.deliveryorder.domain.DeliveryOrderItem;
import com.yserp.project.erp.order.deliveryorder.domain.DeliveryOrderVo;
import com.yserp.project.erp.order.deliveryorder.mapper.DeliveryOrderMapper;
import com.yserp.project.erp.order.deliveryorder.service.IDeliveryOrderItemService;
import com.yserp.project.erp.order.deliveryorder.service.IDeliveryOrderService;
import com.yserp.project.erp.order.saleorder.domain.ErpSaleOrder;
import com.yserp.project.erp.order.saleorder.service.IErpSaleOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 销售发货订单Service业务层处理
 *
 * @author yserp
 * @date 2022-07-26
 */
@Service
public class DeliveryOrderServiceImpl extends ServiceImpl<DeliveryOrderMapper, DeliveryOrder> implements IDeliveryOrderService {

    @Resource
    private DeliveryOrderMapper deliveryOrderMapper;
    @Autowired
    private IDeliveryOrderItemService deliveryOrderItemService;
    @Autowired
    private IErpSaleOrderService saleOrderService;

    /**
     * 查询销售发货订单
     *
     * @param id 销售发货订单主键
     * @return 销售发货订单
     */
    @Override
    public DeliveryOrderVo selectDeliveryOrderById(Long id) {
        return DeliveryOrderVo.builder()
                .deliveryOrder(deliveryOrderMapper.selectById(id))
                .items(deliveryOrderItemService.selectDeliveryOrderItemListByMainId(id))
                .build();

    }

    /**
     * 查询销售发货订单列表
     *
     * @param deliveryOrder 销售发货订单
     * @return 销售发货订单
     */
    @Override
    public List<DeliveryOrder> selectDeliveryOrderList(DeliveryOrder deliveryOrder) {
        QueryWrapper<DeliveryOrder> queryWrapper = new QueryWrapper<>();
        MybatisPlusUtil.notNullField(deliveryOrder, queryWrapper);
        return deliveryOrderMapper.selectList(queryWrapper);
    }

    /**
     * 新增销售发货订单
     *
     * @param deliveryOrderDto 销售发货订单
     * @return 结果
     */
    @Override
    public int insertDeliveryOrder(DeliveryOrderDto deliveryOrderDto) {
        List<DeliveryOrderItem> items = deliveryOrderDto.getItems();
        if (CollectionUtils.isEmpty(items)) {
            throw new BusinessException("子表不能为空");
        }
        //验证单号是否存在
        String orderNo = deliveryOrderDto.getOrderCode();
        if(StringUtils.isBlank(orderNo)){
            throw new BusinessException("单号不存在");
        }
        Integer count = deliveryOrderMapper.selectCount(new QueryWrapper<DeliveryOrder>().eq("order_code", orderNo));
        if(count>0){
            //处理单号，并重新插入缓存
            Integer number = deliveryOrderMapper.selectCount(new QueryWrapper<DeliveryOrder>().like("order_code", orderNo.substring(0,orderNo.length()-3)));
            OrderEnums.putCacheOrderNo(orderNo,number);
            throw new BusinessException("单号已存在，请重新下单");
        }else{
            OrderEnums.putCacheOrderNo(orderNo);
        }
        //插入主表
        DeliveryOrder deliveryOrder = new DeliveryOrder();
        BeanUtils.copyBeanProp(deliveryOrder, deliveryOrderDto);
        int i = deliveryOrderMapper.insert(deliveryOrder);
        //批量插入子表
        items.stream().forEach(item-> item.setMainId(deliveryOrder.getId()));
        deliveryOrderItemService.saveBatch(items);
        return i;
    }

    /**
     * 修改销售发货订单
     *
     * @param deliveryOrderDto 销售发货订单
     * @return 结果
     */
    @Override
    public int updateDeliveryOrder(DeliveryOrderDto deliveryOrderDto) {
        List<DeliveryOrderItem> items = deliveryOrderDto.getItems();
        if(CollectionUtils.isEmpty(items)){
            throw new BusinessException("子表不能为空");
        }
        //修改主表
        DeliveryOrder deliveryOrder = new DeliveryOrder();
        BeanUtils.copyBeanProp(deliveryOrder, deliveryOrderDto);
        int i = deliveryOrderMapper.updateById(deliveryOrder);
        //子表
        Long mainId = deliveryOrder.getId();
        //获取子表
        List<DeliveryOrderItem> deliveryOrderItems = deliveryOrderItemService.selectDeliveryOrderItemListByMainId(mainId);
        if(!CollectionUtils.isEmpty(deliveryOrderItems)) {
            List<Long> oldIds = deliveryOrderItems.stream().map(DeliveryOrderItem::getId).collect(Collectors.toList());
            List<Long> newIds = items.stream().map(DeliveryOrderItem::getId).collect(Collectors.toList());
            oldIds.removeAll(newIds);
            if (!CollectionUtils.isEmpty(oldIds)) {
                deliveryOrderItemService.removeByIds(oldIds);
            }
        }
        for (DeliveryOrderItem item : items) {
            item.setMainId(mainId);
            deliveryOrderItemService.saveOrUpdate(item);
        }
        return i;
    }

    /**
     * 批量删除销售发货订单
     *
     * @param ids 需要删除的销售发货订单主键
     * @return 结果
     */
    @Override
    public int deleteDeliveryOrderByIds(String ids) {
        int result = 0;
        Long[] mainIds = Convert.toLongArray(ids);
        for (Long id : mainIds ) {
            result =this.deleteDeliveryOrderById(id);
            if(result <= 0){
                break;
            }
        }
        return result;
    }

    /**
     * 删除销售发货订单信息
     *
     * @param id 销售发货订单主键
     * @return 结果
     */
    @Override
    public int deleteDeliveryOrderById(Long id) {

        int result = 0;
        //更新主表
        int i=deliveryOrderMapper.deleteById(id);
        //查询子表信息
        List<DeliveryOrderItem> items = deliveryOrderItemService.selectDeliveryOrderItemListByMainId(id);
        if(!CollectionUtils.isEmpty(items)) {
            List<Long> itemIds = items.stream().map(DeliveryOrderItem::getId).collect(Collectors.toList());
            boolean b = deliveryOrderItemService.removeByIds(itemIds);
            if (i > 0 && b) {
                result = 1;
            }
        }
        return result;
    }

    @Override
    public int auditDeliveryOrderByIds(String ids) {
        List<DeliveryOrder> list = new ArrayList<>();
        DeliveryOrder deliveryOrder = null;
        Long[] mainIds = Convert.toLongArray(ids);
        for (Long id : mainIds ) {
            deliveryOrder = new DeliveryOrder();
            deliveryOrder.setId(id);
            //审核通过
            deliveryOrder.setOrderStatus(CheckStatusEnums.OK_CHECK.getCode());
            list.add(deliveryOrder);
        }
        boolean flag = this.updateBatchById(list);
        if(flag){
            return 1;
        }
        return 0;
    }

    @Override
    public int deliveryStatus(DeliveryOrder deliveryOrder) {
        //更新生产单状态
        Long id = deliveryOrder.getId();
        String status = deliveryOrder.getDeliveryStatus();
        if(null == id || StringUtils.isEmpty(status)){
            throw new BusinessException("获取入参为空");
        }
        //查询主数据
        DeliveryOrder delivery = deliveryOrderMapper.selectById(id);
        Long saleOrderId = delivery.getSaleOrderId();
        if(null != saleOrderId){
            //更新生产状态
            ErpSaleOrder erpSaleOrder = new ErpSaleOrder();
            erpSaleOrder.setId(saleOrderId);
            erpSaleOrder.setDeliveryStatus(status);
            saleOrderService.updateErpSaleOrderStatus(erpSaleOrder);
        }
        //更新状态
        DeliveryOrder update = new DeliveryOrder();
        update.setId(id);
        update.setDeliveryStatus(status);
        return deliveryOrderMapper.updateById(deliveryOrder);
    }
}
